package com.bestcem.xm.wallet.util.business;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bestcem.xm.wallet.config.properties.WalletConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @date 2022/6/22 10:48
 */
@Component
public class CheckSignUtil {

    @Autowired
    private WalletConfig walletConfig;

    /**
     * 钱包回调http请求验签
     *
     * @param request     请求
     * @param requestBody 请求体实例
     * @return true 验签通过
     */
    public boolean checkWalletCallbackSign(HttpServletRequest request, Object requestBody) {

        String walletTimestamp = request.getHeader("Wallet-Timestamp");
        String walletNonce = request.getHeader("Wallet-Nonce");
        String walletSignature = request.getHeader("Wallet-Signature");

        // 序列化字段名必须为蛇形
        String jsonBody = JSON.toJSONString(requestBody, SerializerFeature.SortField, SerializerFeature.MapSortField);
        String data = String.join("\n", Arrays.asList(walletTimestamp, walletNonce, walletConfig.getSignKey(), jsonBody));
        String checkedSign = DigestUtil.md5Hex(data);

        return checkedSign.equals(walletSignature);
    }
}
